package com.bjb.vr.common.service;

import cn.hutool.core.lang.UUID;
import com.bjb.vr.common.constant.AliOssConstants;
import com.bjb.vr.common.exception.CommonException;
import com.bjb.vr.common.utils.AliyunOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 阿里云文件管理服务
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/4/14 11:31
 */
@Slf4j
@RefreshScope
@Service
@Configuration
@ConditionalOnProperty(prefix = "spring.file.upload.service", name = "selection", havingValue = "aliyun", matchIfMissing = true)
public class AliyunOperationService implements FileOperationService {

    @Override
    public String uploadFile(MultipartFile multipartFile) {
        AliyunOssUtil ossUtil = new AliyunOssUtil.Builder().build(AliOssConstants.ENDPOINT, AliOssConstants.ACCESS_KEY_ID, AliOssConstants.ACCESS_KEY_SECRET);
        try {
            log.info("开始上传文件：{}", multipartFile.getOriginalFilename());
            String fileID = UUID.fastUUID().toString().split("-")[4];
            File file = new File(multipartFile.getOriginalFilename());
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
            ossUtil.upload(file, fileID);
            log.info("上传文件成功：{}", multipartFile.getOriginalFilename());
            return fileID + "." + FilenameUtils.getExtension(file.getPath());
        } catch (IOException e) {
            throw new CommonException(e.getMessage());
        }
    }

    @Override
    public String downloadFile(String fileName) {
        AliyunOssUtil ossUtil = new AliyunOssUtil.Builder().build(AliOssConstants.ENDPOINT, AliOssConstants.ACCESS_KEY_ID, AliOssConstants.ACCESS_KEY_SECRET);
        try {
            return ossUtil.getFileUrl(fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] downloadFileBytes(String fileName) {
        return new byte[0];
    }
}
